#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Simple HTTP GET Test Script for SMS Receiver
Uses only standard library - no external dependencies
"""

import urllib.request
import urllib.error
import random
import time

def generate_random_code(length=6):
    """Generate random verification code"""
    return ''.join([str(random.randint(0, 9)) for _ in range(length)])

def test_http_get(host='localhost', port=8889):
    """Test HTTP GET request with SMS message parameter"""

    # Generate random verification code and complete SMS message
    code = generate_random_code(6)
    sms_messages = [
        f"Your verification code is {code}, please use within 5 minutes.",
        f"Verification code: {code}, please use within 5 minutes.",
        f"Dynamic password {code}, valid for 3 minutes.",
        f"WeChat login code: {code}",
        f"Bank security code: {code} for transaction verification."
    ]

    import random
    message = random.choice(sms_messages)
    sender = random.choice(["10086", "WeChat", "Bank", "Service", "10010"])

    # Build URL with message and sender parameters
    import urllib.parse
    encoded_message = urllib.parse.quote(message)
    encoded_sender = urllib.parse.quote(sender)
    url = f"http://{host}:{port}/?message={encoded_message}&sender={encoded_sender}"

    print("HTTP GET Test for SMS Receiver")
    print("=" * 60)
    print(f"Sender: {sender}")
    print(f"Message: {message}")
    print(f"URL: {url}")
    print("=" * 60)
    
    try:
        # Send GET request
        request = urllib.request.Request(url)
        with urllib.request.urlopen(request, timeout=5) as response:
            status_code = response.getcode()
            response_text = response.read().decode('utf-8')
            
            print(f"Status Code: {status_code}")
            print(f"Response: {response_text}")
            
            if status_code == 200:
                print("? HTTP GET request sent successfully!")
            else:
                print(f"? HTTP GET request failed with status {status_code}")
            
    except urllib.error.URLError as e:
        if "Connection refused" in str(e) or "10061" in str(e):
            print("? Connection refused - SMS Receiver app not running or HTTP listener not started")
        else:
            print(f"? URL Error: {e}")
    except Exception as e:
        print(f"? Error: {e}")

def test_multiple_messages(host='localhost', port=8889, count=3):
    """Test multiple HTTP GET requests with different SMS messages"""

    print(f"Testing {count} HTTP GET requests with different SMS messages")
    print("=" * 70)

    for i in range(count):
        code = generate_random_code(6)
        messages = [
            f"Your verification code is {code}, please use within 5 minutes.",
            f"Verification code: {code}, please use within 5 minutes.",
            f"Dynamic password {code}, valid for 3 minutes.",
            f"WeChat login code: {code}",
            f"Bank security code: {code} for transaction."
        ]

        import random
        message = random.choice(messages)
        sender = random.choice(["10086", "WeChat", "Bank", "Service", "10010"])

        import urllib.parse
        encoded_message = urllib.parse.quote(message)
        encoded_sender = urllib.parse.quote(sender)
        url = f"http://{host}:{port}/?message={encoded_message}&sender={encoded_sender}"

        print(f"\n[{i+1}/{count}] Testing SMS:")
        print(f"  Sender: {sender}")
        print(f"  Message: {message}")
        print(f"  URL: {url[:80]}..." if len(url) > 80 else f"  URL: {url}")
        
        try:
            request = urllib.request.Request(url)
            with urllib.request.urlopen(request, timeout=5) as response:
                status_code = response.getcode()
                response_text = response.read().decode('utf-8')
                print(f"Status: {status_code}, Response: {response_text}")
                
                if status_code == 200:
                    print("? Success")
                else:
                    print(f"? Failed with status {status_code}")
                    
        except urllib.error.URLError as e:
            if "Connection refused" in str(e) or "10061" in str(e):
                print("? Connection refused")
            else:
                print(f"? URL Error: {e}")
        except Exception as e:
            print(f"? Error: {e}")
        
        # Wait between requests
        if i < count - 1:
            print("Waiting 2 seconds...")
            time.sleep(2)
    
    print(f"\n{'='*70}")
    print("Multiple HTTP GET tests completed!")

def test_error_cases(host='localhost', port=8889):
    """Test error cases"""

    print("Testing HTTP GET error cases")
    print("=" * 50)

    test_cases = [
        (f"http://{host}:{port}/", "No parameters"),
        (f"http://{host}:{port}/?invalid=123", "Wrong parameter name"),
        (f"http://{host}:{port}/?message=", "Empty message parameter"),
        (f"http://{host}:{port}/?sender=test", "Missing message parameter"),
    ]
    
    for i, (url, description) in enumerate(test_cases, 1):
        print(f"\n[{i}] {description}")
        print(f"URL: {url}")
        
        try:
            request = urllib.request.Request(url)
            with urllib.request.urlopen(request, timeout=5) as response:
                status_code = response.getcode()
                response_text = response.read().decode('utf-8')
                print(f"Status: {status_code}, Response: {response_text}")
        except urllib.error.HTTPError as e:
            print(f"HTTP Error {e.code}: {e.read().decode('utf-8')}")
        except Exception as e:
            print(f"Error: {e}")

if __name__ == "__main__":
    import sys
    
    host = 'localhost'
    port = 8889  # HTTP port (now the main and only port)
    
    if len(sys.argv) > 1:
        if sys.argv[1] == '--multiple':
            test_multiple_messages(host, port, 5)
        elif sys.argv[1] == '--errors':
            test_error_cases(host, port)
        else:
            host = sys.argv[1]
            if len(sys.argv) > 2:
                port = int(sys.argv[2])
            test_http_get(host, port)
    else:
        print("HTTP GET Test Options:")
        print("python simple_http_test.py                    # Single SMS test")
        print("python simple_http_test.py --multiple         # Multiple SMS tests")
        print("python simple_http_test.py --errors           # Error case tests")
        print("python simple_http_test.py [host] [port]      # Custom host/port")
        print()
        print("URL Format: http://host:port/?message=sms_content&sender=sender_name")
        print("Examples:")
        print("  http://localhost:8889/?message=Your code is 123456&sender=10086")
        print("  http://192.168.1.100:8889/?message=Verification code 654321&sender=WeChat")
        print()
        test_http_get(host, port)
